package com.eling.elcms.system.webapp.controller;

import com.eling.elcms.core.exception.AppException;
import com.eling.elcms.core.webapp.controller.BaseFormController;
import com.eling.elcms.fm.service.IFileService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;

@Controller
public class AttachmentController extends BaseFormController {
private static final Logger log = LoggerFactory.getLogger(AttachmentController.class);
	
	public static final String DEFAULT_JPEG = ObjectUtils.CONST("/assets/eling/resources/nophoto.svg");

	@Autowired
	public IFileService fileService;
	

	/**
	 * 上传文件
	 * @param file
	 * @param type
	 * @param name
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value="/api/attachment/**/{name:.+}",method = RequestMethod.POST)
	@ResponseBody
	public void upload(@RequestParam("file") CommonsMultipartFile file,
			@PathVariable("name") String name,
			HttpServletRequest rep,
			HttpServletResponse resp) throws IOException{
		
        String urlpath = getFilePath(rep);
        
		urlpath = URLDecoder.decode(urlpath, "UTF-8");
    
		String filePath = fileService.save(file.getInputStream(), urlpath);
		
		if(filePath != null){
			resp.setStatus(HttpStatus.OK.value());
		}else{
			resp.setStatus(HttpStatus.BAD_REQUEST.value());
		}
			
	}
	
	
	/**
	 * 获取文件
	 * @param type
	 * @param name
	 * @return
	 */
	@RequestMapping(value="/api/attachment/**/{name:.+}",method = RequestMethod.GET)
	@ResponseBody
	public void read(
			@PathVariable("name") String name,
			HttpServletRequest req,
			HttpServletResponse resp){
		
        // 去掉 URI 中的 context path  
        String urlpath = getFilePath(req);
		
        InputStream is = fileService.read(urlpath);
        try {
        	resp.reset();
        	if(null != is){
        		OutputStream os = resp.getOutputStream();
        		IOUtils.copy(is, os);
        		os.flush();
    			os.close();
    			is.close();
        	}else{
    			//判断返回文件，如果没有为null则返回404
        		if(req.getHeader("Accept").indexOf("image") > -1){
        			resp.addHeader("Content-Type", "image/svg+xml");
        			resp.getOutputStream().write(readDefaultJegp());
        		}else{
        			resp.setStatus(HttpStatus.NOT_FOUND.value());	
        		}
        	}
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
	}
	
	
	/**
	 * 获取文件路径
	 * @param rep
	 * @return
	 */
	private String getFilePath(HttpServletRequest rep){
		
		String context = "api/attachment";  
        String uri = rep.getRequestURI();  
		return uri.substring(uri.indexOf(context)+context.length());
	}
	
	private byte[] readDefaultJegp() {
		try {
			return IOUtils.toByteArray(getServletContext().getResourceAsStream(DEFAULT_JPEG));
		} catch (IOException e) {
			throw new AppException(e);
		}
	}
	
}
